package com.eims.sls_app.ui;

import org.json.JSONArray;
import org.json.JSONObject;
import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.fragment.NotDrawFragment;
import com.eims.sls_app.fragment.WinDrawFragment;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.AppTools;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.view.MyToast;

import bls.juejin.cn.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class GamecenterActivity extends MyFragmentActivity implements OnClickListener, OnCheckedChangeListener {
	private static final String TAG = "GamecenterActivity";
	private ImageView btn_back;
	private RelativeLayout ll_surplus;//进入抽奖界面
	private TextView tv_surplus;
	private ListView lv_Not_draw,lv_Already_winning;
	private int count = 0;
	private MyHandler myHandler;
	private MyAsynTask myAsynTask;
	
	private String opt, auth, info, time, imei, crc, key; // 格式化后的参数
	private String[] SchemeNumber;
	private String[] DataTime;
	private RadioButton rb_winButton;
	private RadioButton rb_notWin;
	private RadioGroup rg_tab;
	private NotDrawFragment notDrawFragment;//未抽奖
	private WinDrawFragment winDrawFragment;//已中奖
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game_center);
		myHandler = new MyHandler();
		App.activityS.add(this);
		App.activityS1.add(this);
		initView();
		initData();
		setListener();
		//showWinFragment();
	}
	@Override
	public Resources getResources() {
		// TODO Auto-generated method stub
		Resources res = super.getResources();
		Configuration config = new Configuration();
		config.setToDefaults();
		res.updateConfiguration(config, res.getDisplayMetrics());
		return res;
	}
	private void setListener() {
		btn_back.setOnClickListener(this);
		ll_surplus.setOnClickListener(this);
		rg_tab.setOnCheckedChangeListener(this);
	}

	private void initData() {
		myAsynTask = new MyAsynTask();
		myAsynTask.execute();
		getText2(count);
		rg_tab.check(R.id.rb_Already_win);
		showWinFragment();
		
	}

	private void getText2(int count2) {
		Spanned text = Html.fromHtml(AppTools.changeStringColor("#060607", "您还有 ")
				+ AppTools.changeStringColor("#e3393c", count + "")+ AppTools.changeStringColor("#060607", " 次抽奖机会。"));
		if (count==0) {
			tv_surplus.setText("您的抽奖机会已经用完");
		}else {
			tv_surplus.setText(text);
			//notDrawAdapter = new NotDrawAdapter(DataTime, GamecenterActivity.this);
			//lv_Not_draw.setAdapter(notDrawAdapter);
			
		}
		
		
	}

	private void initView() {
		btn_back = (ImageView) findViewById(R.id.btn_back);
		ll_surplus = (RelativeLayout) findViewById(R.id.ll_surplus);
		tv_surplus = (TextView) findViewById(R.id.tv_surplus);
		rg_tab = (RadioGroup) findViewById(R.id.tab_game);
		rb_winButton = (RadioButton) findViewById(R.id.rb_Already_win);
		rb_notWin = (RadioButton) findViewById(R.id.rb_Not_draw);
		//lv_Not_draw = (ListView) findViewById(R.id.lv_not_draw);
		
		
		
	}
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.ll_surplus:
			Intent intent = new Intent(this, Luck_drawActivity.class);
			intent.putExtra("type", count);
			intent.putExtra("SchemeNumber", SchemeNumber);
			startActivity(intent);
			break;
		

		default:
			break;
		}
		
	}
	
	public void showWinFragment(){
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideAllFragment(fragmentTransaction);
        if(winDrawFragment == null){
        	winDrawFragment = WinDrawFragment.newInstance();
            fragmentTransaction.add(R.id.fragmentContent,winDrawFragment);
        }
        commitShowFragment(fragmentTransaction,winDrawFragment);
    }
	public void showNotWinFragment(){
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideAllFragment(fragmentTransaction);
        if(notDrawFragment == null){
        	notDrawFragment = NotDrawFragment.newInstance(DataTime);
            fragmentTransaction.add(R.id.fragmentContent,notDrawFragment);
        }
        commitShowFragment(fragmentTransaction,notDrawFragment);
    }

	private void commitShowFragment(FragmentTransaction fragmentTransaction,
			Fragment fragment) {
		fragmentTransaction.show(fragment);
        fragmentTransaction.commit();
		
	}

	private void hideAllFragment(FragmentTransaction fragmentTransaction) {
		hideFragment(fragmentTransaction,winDrawFragment);
		hideFragment(fragmentTransaction,notDrawFragment);
		
		
	}
	private void hideFragment(FragmentTransaction fragmentTransaction,Fragment fragment){
        if(fragment!=null){
            fragmentTransaction.hide(fragment);
        }
    }

	private void backToHall() {
		Intent intent = new Intent(getApplicationContext(), MainActivity.class);
		this.startActivity(intent);
		this.finish();
		
	}
	
	/** 异步任务 */
	class MyAsynTask extends AsyncTask<Void, Integer, String> {

		

		/** 在后台执行的程序 */
		@Override
		protected String doInBackground(Void... params) {
			int p;
			info = "";

			//Log.i("x", "获得我全部投注记录    info  " + info);

			opt = "82";
			if (App.user==null) {
				crc = RspBodyBaseBean.getCrc(time, imei, key, info,
						"-1");
				auth = RspBodyBaseBean.getAuth(crc, time, imei,
						"-1");
			}else {
				crc = RspBodyBaseBean.getCrc(time, imei, key, info,
						App.user.getUid());
			auth = RspBodyBaseBean.getAuth(crc, time, imei,
						App.user.getUid());
			}
			
				Log.i(TAG,"抽奖>"+ RequestParams.convertParams(GamecenterActivity.this, opt, info));
			String[] values = { opt, auth, info };
			String result = HttpUtils.doPost(App.names, values,
					App.path);

			Log.e("x", "得到所有抽奖内容   " + result);
			// MyToast.getToast(context, result);

			if ("-500".equals(result))
				return result;

			if (null == result)
				return "1";
			// 04-06 10:22:49.214: I/qtaguid(1826): Untagging socket 88 failed
			// errno=-13

			try {

				JSONObject item = new JSONObject(result);

				count = item.optInt("count"); 
				
				JSONArray array;
				try {
					array = new JSONArray(item.optString("list"));
					if (array==null) {
						return "1";
					}else {
						SchemeNumber = new String[array.length()];
						DataTime = new String[array.length()];
						
						for (int i = 0; i < array.length(); i++) {
							try {
								
								JSONObject items = array.getJSONObject(i);
								
								SchemeNumber[i] = items.optString("SchemeNumber");
								DataTime[i] = items.optString("DateTime");
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				

				if (this.isCancelled()) {
					Log.i("x", "取消了异步。。。。");
					return null;
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.i("x", "myAllLottery 错误" + e.getMessage());
			}

			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			if (null == result)
				return;
			if ("1".equals(result)) {
				myHandler.sendEmptyMessage(-1);
			}

			myHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}
	
	/** 进行页面刷新 */
	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				getText2(count);
				
				break;
			case -1:
				Toast.makeText(getApplication(), "数据为空", Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.rb_Already_win:
			showWinFragment();
			break;
		case R.id.rb_Not_draw:
			showNotWinFragment();
			break;

		default:
			break;
		}
		
	}
	
	
}
